import dayjs from 'dayjs'

/**
 * Parse the time to string
 * @param {(Date|string|number)} time
 * @param {string} format
 * @returns {string}
 */
export function formatDateTime(dateTime, format) {
	if (arguments.length === 0) {
		return dateTime
	}
	if (!dateTime) { return ''; }
	if (!dayjs(dateTime).isValid()) { return dateTime; }

	const cFormat = format || 'YYYY-MM-DD HH:mm:ss'
	return dayjs(dateTime).format(cFormat);
}

/**
 * Parse the time to fromNow
 * @param {(Date|string|number)} time
 * @returns {string}
 */
export function fromNow(dateTime) {
	if (!dateTime) { return dateTime; }
	if (!dayjs(dateTime).isValid()) { return dateTime; }
	return dayjs(dateTime).fromNow();
}

/**
 * Parse the time to formatMillisecond
 * @param {(string|number)} millisecond
 * @returns {string}
 */
export function formatMillisecond(millisecond) {
	var result = `0"`;
	if (!millisecond) {
		return result;
	}
	const minute = Math.floor(dayjs.duration(millisecond).asMinutes());
	const second = dayjs.duration(millisecond).seconds();

	if (minute > 0) {
		result = `${minute}'${second}"`;
	} else {
		result = `${second}"`;
	}
	return result;
}

/**
 * Parse the time to string
 * 获取当前月的第一天并格式化日期
 * @param {string} format
 * @returns {string}
 */
 export function formatStartDate(format) {
	const now = new Date(); // 当前日期 
	const nowMonth = now.getMonth(); // 当前月 
	let nowYear = now.getYear(); // 当前年 
	nowYear += (nowYear < 2000) ? 1900 : 0;
	const monthStartDate = new Date(nowYear, nowMonth, 1);
	const cFormat = format || 'YYYY-MM-DD HH:mm:ss'
	return dayjs(monthStartDate).format(cFormat);
}
